/*
 * @Author       : heyongfeng
 * @Date         : 2021-06-30 16:03:36
 * @Description  : 入口
 * @LastEditors  : heyongfeng
 * @LastEditTime : 2021-07-01 14:32:12
 */
import { Options, ExtraInfo } from './options'
import getVersion from './util'

function getVersionFile(extraInfo: ExtraInfo) {
  let content = JSON.stringify({ ...getVersion(), extraInfo }, null, 4)
  return {
    source() {
      return content
    },
    size() {
      return content.length
    }
  }
}

export default class {
  fileName: string
  extraInfo: ExtraInfo
  constructor(options: Options | string) {
    if (typeof options === 'string') {
      options = { fileName: options }
    } else {
      options = options || {}
    }
    const { fileName, extraInfo } = options
    this.fileName = fileName || 'projectInfo.json'
    this.extraInfo = extraInfo || {}
  }
  apply(compiler: any) {
    if (!compiler.hooks) {
      compiler.plugin('emit', (compilation: any, callback: Function) => {
        compilation.assets[this.fileName] = getVersionFile(this.extraInfo)
        callback()
      })
    } else {
      compiler.hooks.compilation.tap(
        'BuildVersionPlugin',
        (compilation: any) => {
          compiler.hooks.emit.tap('BuildVersionPlugin', () => {
            compilation.assets[this.fileName] = getVersionFile(this.extraInfo)
          })
        }
      )
    }
  }
}
